import { PiniaPlugin, PiniaPluginContext } from 'pinia';
interface Option {
  notPersistedStateIds: string[];
}
interface Storage {
  getItem: (key: string) => any;
  setItem: (key: string, value: any) => void;
  removeItem: (key: string) => void;
}

function createPersistedState (option: Option | null): PiniaPlugin {
  const storage = window.localStorage;
  const key = 'app';
  const notPersistedStateIds = option ? option.notPersistedStateIds : <string[]>[];
  const getState = (key2: string, storage2: Storage) => {
    const value = storage2.getItem(key2);
    if (typeof value === 'string') {
      if (JSON.parse(value)) {
        return JSON.parse(value);
      } else {
        if (typeof value === 'object') {
          return value;
        } else {
          return null;
        }
      }
    }
  };
  const setState = (key2: string, state: any, storage2: Storage) => {
    storage2.setItem(key2, JSON.stringify(state));
  };
  return (context: PiniaPluginContext) => {
    const store = context.store;
    if (!notPersistedStateIds.includes(store.$id)) {
      const tempKey = `${key}-${store.$id}`;
      const data = getState(tempKey, storage);
      // 第一次启动时，从localStorage里面取出数据并更新pinia
      if (data) {
        store.$patch(data);
      }
    }

    // state里面数据变动了，则重新设置localStorage里面的值
    store.$subscribe((mutation, state) => {
      if (!notPersistedStateIds.includes(mutation.storeId)) {
        const tempKey2 = `${key}-${mutation.storeId}`;
        setState(tempKey2, state, storage);
      }
    });
  };
}
export default createPersistedState;
